import env from '../utils/env'

/**
 * fetch api返回的是一个promise对象, 支持异步编程 离线性能更佳
 */
export default async (url = '',data = {},type = 'get',method = 'fetch') =>{
    type = type.toUpperCase();
    url = env.baseUrl + url ;

    if(type == 'GET'){
        let dataStr = '';//数据拼接 , 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
        Object.keys(data).forEach(key =>{
            dataStr += '&' + key + '=' + data[key]; //如果含有中文怎么处理
        })

        if(dataStr){
            dataStr = dataStr.slice(1);
            url = url + '?' + dataStr;
        }
    }

    if(window.fetch && method == 'fetch'){
        let config = {
            credentials:'include',
            method : type,
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            mode:'cors',//将mode 设置为 cors 即可
            cache:'force-cache'
        }

        if(type =='POST'){
            Object.defineProperty(config,'body',{
                value:JSON.stringify(data)
            })

            console.log(config);
        }
   
        const response = await fetch(url,config);
        console.log(response);
        const responseJson = await response.json();
        console.log('responseJson ' + JSON.stringify(responseJson));
        if(responseJson.code === 0){
            return responseJson.data;
        }
    }else{
        //如果浏览器不支持fetch方法，采用xmlHttpRequest进行异步请求
        return new Promise((resolve,reject) =>{
            let requestObj;
            if(window.XMLHttpRequest){
                requestObj = new XMLHttpRequest();
            }else{
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if(type == 'POST'){
                sendData = JSON.stringify(data); //请求的data数据
            }

            requestObj.open(type,url,true);
            requestObj.setRequestHeader('Content-type','application/x-www-form-urlencoded')
            requestObj.send(sendData);
            requestObj.onreadystatechange = () => {
                if(requestObj.readyState == 4){
                    if(requestObj.status === 200){
                        let obj = requestObj.response;
                        if(typeof obj !== 'object'){
                            obj = JSON.parse(obj); 
                        }
                         resolve(obj);//返回200状态码
                    } else{
                        reject(requestObj);
                    }
                }
            }
        })
    }

}